import { Component, OnInit, Input, OnChanges, SimpleChanges, Output, EventEmitter } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { List } from 'linqts';

import { Farm } from '../../../../entity/farm.model';
import { Phase } from '../../../../entity/phase.model';
import { Device } from '../../../../entity/device.model';
import { Model } from '../../../../entity/model.model';
import { Circuit } from '../../../../entity/circuit.model';

import { ApplicationService } from '../../../../service/application.service';
import { PhaseService } from '../../../../service/phase.service';
import { CircuitService } from '../../../../service/circuit.service';
import { ModelService } from '../../../../service/model.service';
import { DeviceService } from '../../../../service/device.service';
import { DeviceCategoryService } from '../../../../service/device-category.service';
import { DeviceCategory } from '../../../../entity/device-category.model';
import { FarmCategoryEnum } from '../farm-category.enum';
import { DeviceCategoryEnum } from '../device-category.enum';
import { DeviceGroupItem } from '../device-group-item';

@Component({
  selector: 'app-device-selector',
  templateUrl: './device-selector.component.html',
  styleUrls: ['./device-selector.component.css']
})
export class DeviceSelectorComponent implements OnInit, OnChanges {

  /**
   * 电站类别
   * 默认:FarmCategoryEnum.winfarm 风场
   * @type {FarmCategory}
   * @memberof DeviceSelectorComponent
   */
  @Input() farmCategory: FarmCategoryEnum;
  /**
   * 设备类别
   * 默认:DeviceCategoryEnum.turbine 风机
   * @type {DeviceCategoryEnum}
   * @memberof DeviceSelectorComponent
   */
  @Input() deviceCategories: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine];
  /**
   * 被选中的电站
   * 默认:null
   * @type {Farm}
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedFarm: any = null;
  /**
   * 被选中设备
   * 默认:null
   * @type {Farm}
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedDevice: Device = null;
  /**
   * 被选中的风场Id
   * 
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedFarmId = 0;
  /**
   * 被选中的设备Id
   * 
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedDeviceId = 0;
  /**
   * 被移除的设备
   * 默认:null
   * @type {Farm}
   * @memberof DeviceSelectorComponent
   */
  @Input() removeDevice: Device = null;
  /**
   * 是否展示分组工具条
   * 
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() displayGroupToolbar = true;
  /**
   * 限制设备选择数量
   * 默认:0
   * 0不做限制
   * @type {number}
   * @memberof DeviceSelectorComponent
   */
  @Input() choiceDeviceCount;
  /**
   *刚进页面是默认选择风机数量
   *默认:null 不做限制
   * 0不选择
   * @memberof DeviceSelectorComponent
   */
  @Input() defaultChooseDeviceCount;
  /**
   *在只能选择一个风场情况下，点击不同风场风机 
   *清除之前选择风机为true
   *提示只能选择一个风场为false
   *默认为false
   * @memberof DeviceSelectorComponent
   */
  @Input() isClearSelectDevice = false;
  /**
   * 限制多选风场
   * 默认：false
   * false不允许多选
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() multipleFarm = false;
  /**
   * 限制多选设备
   * 默认：true
   * false不允许多选
   * 如果为 false
   * multipleFarm
   * multipleModel
   * choiceDeviceCount
   * 将不起任何作用
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() multipleDevice = true;
  /**
   * 限制多选型号
   * 默认：false
   * false不允许多选
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() multipleModel = true;
  /**
   * 是否展示
   * 
   * @memberof DeviceSelectorComponent
   */
  @Input() display = false;
  /**
   *分组默认选中
   *
   * @type {DeviceGroupCategoryEnum}
   * @memberof DeviceSelectorComponent
   */
  @Input() deviceGroupCategory: DeviceGroupCategoryEnum = DeviceGroupCategoryEnum.none;
  /**
   *默认只选择一条线路
   *
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() selectAGroup: boolean;

  /**
   * 选中的设备
   * 
   * @memberof DeviceSelectorComponent
   */
  @Output() selectedDevicesChange = new EventEmitter<Device[]>();


  public farms: Farm[] = [];
  public deviceGroups: DeviceGroupItem[] = [];
  public choiceDeviceOver = false;
  public choiceFarmOver = false;
  public choiceModelOver = false;
  public deviceCategoryName = '设备';


  private currentFarmDevices: Device[];
  private phases: Phase[] = [];
  private models: Model[] = [];
  private circuits: Circuit[] = [];
  private allDeviceCategorys: DeviceCategory[] = [];
  private deviceCache: DeviceCache = {};
  private timer: any = null;
  private isFristLoadDevice = false;

  /**
   * Creates an instance of DeviceSelectorComponent.
    * @param {ApplicationService} application 运用程序全局缓存 
    * @param {TurbineService} turbineService 风机服务
    * @param {DeviceService} deviceService 设备服务

   * @memberof DeviceSelectorComponent
   */
  constructor(
    private application: ApplicationService,
    private phaseService: PhaseService,
    private circuitService: CircuitService,
    private modelService: ModelService,
    private deviceService: DeviceService,
    private deviceCategoryService: DeviceCategoryService
  ) {

  }
  /**
   * ngOnInit事件在ngOnChanges之后执行
   * 
   * @memberof DeviceSelectorComponent
   */
  ngOnInit() {
    // debugger
    if (!this.deviceGroupCategory) {
      this.deviceGroupCategory = DeviceGroupCategoryEnum.none;
    }

    this.loadFarms(this.farmCategory);
    const getPhase = this.phaseService.getPhases();
    const getCircuit = this.circuitService.getCircuitList();
    const getModels = this.modelService.getModels();
    const getDevices = this.deviceCategoryService.getDeviceCategorys();
    Promise.all([getPhase, getCircuit, getModels, getDevices])
      .then(res => {
        if (res[0]) {
          this.phases = [...res[0]];
        };
        if (res[1]) {
          this.circuits = [...res[1]];
        };
        if (res[2]) {
          this.models = [...res[2]];
        };
        if (res[3]) {
          this.allDeviceCategorys = [...res[3]];
        };
        this.loadDevices(this.deviceCategories, this.selectedFarm);

      });
  }
  ngOnChanges(changes: SimpleChanges): void {

    if (changes['display'] != null && changes['display'].currentValue != null) {
      if (!changes['display'].firstChange) {
        // 如果dispaly输入属性从ture变成false，表示设备选中项发生改变将触发输出selectedDevicesChange属性
        if (!changes['display'].currentValue && this.multipleDevice) {
          const checkedDevices = this.getCheckedDevices();
          this.selectedDevicesChange.emit(checkedDevices);
        }
      }
    }
    if (changes['removeDevice'] != null && changes['removeDevice'].currentValue != null) {
      const farmIds = Object.getOwnPropertyNames(this.deviceCache);
      farmIds.forEach(farmId => {
        const id = parseInt(farmId, 0);
        const index = this.deviceCache[id].findIndex(device => device.deviceId == this.removeDevice.deviceId);
        if (index > -1) {
          this.deviceCache[id][index].isChecked = false;
        }
      });
    }
    if (changes['selectedFarm'] != null && changes['selectedFarm'].currentValue != null) {

      if (!changes['selectedFarm'].firstChange) {
        if (this.isFristLoadDevice) {
          if (!this.multipleFarm) {
            const checkedDevices = this.getCheckedDevices();
            checkedDevices.forEach(o => o.isChecked = false);
          }
          this.isFristLoadDevice = false;
          this.loadDevices(this.deviceCategories, this.selectedFarm);
        }
      }
    }
    if (changes['selectedFarmId'] != null && changes['selectedFarmId'].currentValue != null) {
      if (!changes['selectedFarmId'].firstChange) {
        if (this.isFristLoadDevice) {
          if (!this.multipleFarm) {
            const checkedDevices = this.getCheckedDevices();
            checkedDevices.forEach(o => o.isChecked = false);
          }
          this.isFristLoadDevice = false;
          this.loadDevices(this.deviceCategories, this.selectedFarm);
        }

      }
    }
  }
  /**
   * 当电站选中发生改变事件
   * 
   * @param {Farm} farm 被选中的电站
   * @returns 
   * @memberof DeviceSelectorComponent
   */
  onFarmSelectedChange(farm: Farm): void {
    this.selectedFarm = farm;
    this.loadDevices(this.deviceCategories, this.selectedFarm);
  }
  /**
   * 点击按某个进行分组的事件
   * 
   * @param {*} ev
   * @returns
   * @memberof DeviceSelectorComponent
   */
  onDeviceGroupCategorySelectedChange(radio: HTMLInputElement): void {
    if (radio.checked) {
      const value = parseInt(radio.value, 0);
      if (this.deviceGroupCategory !== value) {
        this.deviceGroupCategory = value;
        this.devicesGroup(this.currentFarmDevices, this.deviceGroupCategory);
      }
    }
  }
  /**
   * 电站级别下的设备的全选和全不选事件
   * 
   * @param {boolean} checked
   * @memberof DeviceSelectorComponent
   */
  onFarmDeviceChecked(checked: boolean) {
    if (checked === false) {
      this.currentFarmDevices.forEach(device => device.isChecked = false);
    } else {

      this.currentFarmDevices.forEach(device => {
        const checkedDevices = this.getCheckedDevices();
        if (device.isChecked === false) {
          if (this.choiceDeviceCount === null && this.multipleFarm && this.multipleModel) {
            device.isChecked = true;
          } else {


            //if (this.choiceDeviceCount !== 0) {
            device.isChecked = this.checkChoiceDeviceCount(device, checkedDevices);
            if (!device.isChecked) {
              return;
            }
            //}

            if (this.multipleFarm === false) {
              device.isChecked = this.checkMultipleFarm(device, checkedDevices);
              if (!device.isChecked) {
                return;
              }
            }
            if (this.multipleModel === false) {
              device.isChecked = this.checkMultipleModel(device, checkedDevices);
              if (!device.isChecked) {
                return;
              }
            }
          }
        }
      });
    }
  }
  /**
   * 分组条目下的设备全选和全不选事件
   *
   * @param {boolean} checked
   * @param {DeviceGroupItem} deviceGroupItem
   * @memberof DeviceSelectorComponent
   */
  onGroupItemDeviceChecked(checked: boolean, deviceGroupItem: DeviceGroupItem) {
    if (checked === false) {
      deviceGroupItem.devices.forEach(device => device.isChecked = false);
    } else {
      deviceGroupItem.devices.forEach(device => {
        const checkedDevices = this.getCheckedDevices();
        if (device.isChecked === false) {
          if (this.choiceDeviceCount === 0 && this.multipleFarm && this.multipleModel) {
            device.isChecked = true;
          } else {
            if (this.choiceDeviceCount !== 0) {
              device.isChecked = this.checkChoiceDeviceCount(device, checkedDevices);
              if (!device.isChecked) {
                return;
              }
            }
            if (this.multipleFarm === false) {
              device.isChecked = this.checkMultipleFarm(device, checkedDevices);
              if (!device.isChecked) {
                return;
              }
            }
            if (this.multipleModel === false) {
              device.isChecked = this.checkMultipleModel(device, checkedDevices);
              if (!device.isChecked) {
                return;
              }
            }
          }
        }
      });
    }
  }
  /**
   * 单设备选择
   *
   * @param {Event} event
   * @param {Device} device
   * @memberof DeviceSelectorComponent
   */
  onDeviceChecked(ev, device: Device) {

    if (ev.target.checked === false) {
      device.isChecked = false;
    } else {
      if (device.isChecked === false) {
        const checkedDevices = this.getCheckedDevices();
        // 允许多选设备
        if (this.multipleDevice) {
          if (this.choiceDeviceCount === 0 && this.multipleFarm && this.multipleModel) {
            device.isChecked = true;
          } else {
            if (this.choiceDeviceCount !== 0) {
              device.isChecked = this.checkChoiceDeviceCount(device, checkedDevices, ev.target);
              if (!device.isChecked) {
                ev.stopPropagation();
                ev.preventDefault();
                return;
              }
            }
            if (this.multipleFarm === false) {
              device.isChecked = this.checkMultipleFarm(device, checkedDevices, ev.target);
              if (!device.isChecked) {
                ev.stopPropagation();
                ev.preventDefault();
                return;
              }
            }
            if (this.multipleModel === false) {
              device.isChecked = this.checkMultipleModel(device, checkedDevices, ev.target);
              if (!device.isChecked) {
                ev.stopPropagation();
                ev.preventDefault();
                return;
              }
            }
          }
        } else { // 不允许多选设备，单选设备的时候 直接触发selectedDevicesChange事件
          if (checkedDevices.length > 0) {
            checkedDevices.forEach(o => o.isChecked = false);
          }
          device.isChecked = true;
          this.selectedDevicesChange.emit([device]);
        }
      }
    }
  }

  private checkChoiceDeviceCount(device: Device, checkedDevices: Device[], check: HTMLInputElement = null): boolean {
    let result = true;
    // 限制选择设备数量
    if (this.choiceDeviceCount !== 0 && this.choiceDeviceCount) {
      if (checkedDevices.length + 1 > this.choiceDeviceCount) {
        result = false;
        if (this.choiceDeviceOver === false) {
          this.choiceDeviceOver = true;
          if (check != null) {
            check.checked = false;
          }
          this.timer = setTimeout(() => {
            this.choiceDeviceOver = false;
            clearTimeout(this.timer);
          }, 1000);
        }
      }
    }
    return result;
  }
  private checkMultipleFarm(device: Device, checkedDevices: Device[], check: HTMLInputElement = null): boolean {
    let result = true;
    // 限制多个电站
    if (!this.multipleFarm) {
      if (checkedDevices.length > 0) {
        const list = new List(checkedDevices);
        const group = list.GroupBy(grouper => grouper.farmId, mapper => mapper.farmId);
        const farmIds = Object.getOwnPropertyNames(group);
        if (farmIds.findIndex(farmId => farmId === device.farmId.toString()) === -1) {
          if (this.isClearSelectDevice) {
            result = true;
            // tslint:disable-next-line:forin
            for (const farmId in this.deviceCache) {
              this.deviceCache[farmId].forEach(d => {
                d.isChecked = false;
              });
            }
          } else {
            result = false;
            if (this.choiceFarmOver === false) {
              this.choiceFarmOver = true;
              if (check != null) {
                check.checked = false;
              }
              this.timer = setTimeout(() => {
                this.choiceFarmOver = false;
                clearTimeout(this.timer);
              }, 1000);
            }
          }

        }
      }
    }
    return result;
  }
  private checkMultipleModel(device: Device, checkedDevices: Device[], check: HTMLInputElement = null): boolean {
    let result = true;
    // 限制多个型号
    if (!this.multipleModel) {
      if (checkedDevices.length > 0) {
        const list = new List(checkedDevices);
        const group = list.GroupBy(grouper => grouper.modelId, mapper => mapper.modelId);
        const modelIds = Object.getOwnPropertyNames(group);
        if (modelIds.findIndex(modelId => modelId === device.modelId.toString()) === -1) {
          result = false;
          if (this.choiceModelOver === false) {
            this.choiceModelOver = true;
            if (check != null) {
              check.checked = false;
            }
            this.timer = setTimeout(() => {
              this.choiceModelOver = false;
              clearTimeout(this.timer);
            }, 1000);
          }
        }
      }
    }
    return result;
  }
  /**
   * 根据类别筛选电站
   * @private
   * @param {FarmCategory} farmCategory 电站类别枚举
   * @memberof DeviceSelectorComponent
   */
  private loadFarms(farmCategory: FarmCategoryEnum): void {
    // debugger
    // 从当前用户拥有的电站访问权限中筛选电站
    if (farmCategory) {
      let farmCategoryCode = '';
      switch (farmCategory) {
        case FarmCategoryEnum.winfarm:
          farmCategoryCode = 'winfarm';
          break;
        case FarmCategoryEnum.photovoltaic:
          farmCategoryCode = 'photovoltaic';
          break;
      }
      this.farms = this.application.currentUserFarms.filter(farm => farm.farmCategory === farmCategoryCode);
    } else {
      this.farms = this.application.currentUserFarms;
    }
    if (this.farms != null && this.farms.length > 0) {

      if (this.selectedFarm == null || this.selectedFarmId === 0) {
        this.selectedFarm = this.farms[0];
      }
      if (this.selectedFarmId !== 0) {

        const index = this.farms.findIndex(farm => farm.farmId == this.selectedFarmId);
        if (index !== -1) {
          this.selectedFarm = this.farms[index];
        } else {
          this.selectedFarm = this.farms[0];
        }
      }
    } else {
      this.farms = [];
    }
  }
  /**
   * 根据类别筛选电站下的设备
   * @private
   * @param {DeviceCategoryEnum} deviceCategory 设备类别
   * @param {Farm} selectedFarm 电站
   * @memberof DeviceSelectorComponent
   */
  private loadDevices(deviceCategorys: DeviceCategoryEnum[], selectedFarm: Farm): void {
    if (selectedFarm != null) {
      const promise: any[] = [];
      // 从缓存中加载设备，如果缓存中没有设备，调用服务加载设备，并且写入缓存
      this.currentFarmDevices = this.getDevicesFromCache(selectedFarm);
      if (this.currentFarmDevices.length <= 0) {
        if (!deviceCategorys || !deviceCategorys.length) {
          promise.push(this.deviceService.getDevicesByFarmId(selectedFarm.farmId));
        } else {
          deviceCategorys.forEach(deviceCategory => {
            promise.push(this.deviceService.getDevicesByFarmIdDeviceCategoryCode(selectedFarm.farmId, '0' + deviceCategory.toString()));
          })
        }
        Promise.all(promise)
          .then(res => {
            const result: Device[] = [];
            res.forEach(devices => devices && result.push(...devices));
            if (result.length > 0) {
              if (!result[0].deviceCategoryName) {
                result.forEach(device => {
                  // tslint:disable-next-line:max-line-length
                  const index = this.allDeviceCategorys.findIndex(deviceCategory => deviceCategory.deviceCategoryId === device.deviceCategoryId);
                  if (index > -1) {
                    device.deviceCategoryName = this.allDeviceCategorys[index].deviceCategoryName.toString();
                  }
                })
              }
              this.commonLoadDevice(result, selectedFarm);
            }
          })
          .catch(err => {
            console.log(err)
          });
      } else {
        this.devicesGroup(this.currentFarmDevices, this.deviceGroupCategory);
      }
    }
  }
  private commonLoadDevice(devices: Device[], selectedFarm: Farm) {
    if (devices !== null && devices.length > 0) {
      devices.forEach(device => {
        device.farmName = selectedFarm.farmName;
        device.farmCode = selectedFarm.farmCode;
        device.phaseName = this.phases.filter(phase => phase.phaseId === device.phaseId).length ? this.phases.filter(phase => phase.phaseId === device.phaseId)[0].phaseName : '';
        device.circuitName = this.circuits.filter(circuit => circuit.circuitId === device.circuitId).length ? this.circuits.filter(circuit => circuit.circuitId === device.circuitId)[0].circuitName : '';
        device.modelName = this.models.filter(model => model.modelId === device.modelId).length ? this.models.filter(model => model.modelId === device.modelId)[0].modelName : '';
        device.isChecked = false;
      });
      this.currentFarmDevices = devices;
      this.setDevicesFromCache(selectedFarm, this.currentFarmDevices);
      this.devicesGroup(this.currentFarmDevices, this.deviceGroupCategory);
    }
  }
  /**
   * 将设备进行分组
   *
   * @private
   * @param {Device[]} devices
   * @param {DeviceGroupCategoryEnum} deviceGroupCategory
   * @memberof DeviceSelectorComponent
   */
  private devicesGroup(devices: Device[], deviceGroupCategory: DeviceGroupCategoryEnum): void {
    this.deviceGroups = [];
    if (devices != null && devices.length > 0) {
      const deviceList: List<Device> = new List(devices);
      switch (deviceGroupCategory) {
        case DeviceGroupCategoryEnum.none:
          const deviceGroups = deviceList.GroupBy(grouper => grouper.deviceCategoryName, mapper => mapper);

          const devicesCategorys = Object.getOwnPropertyNames(deviceGroups);
          devicesCategorys.forEach(deviceCategoryName => {
            const deviceDivices = Object.getOwnPropertyDescriptor(deviceGroups, deviceCategoryName).value;
            this.deviceGroups.push({
              title: deviceCategoryName,
              isChecked: false,
              devices: deviceDivices,
            });
          });
          break;
        case DeviceGroupCategoryEnum.byPhase:
          const phaseGroups = deviceList.GroupBy(grouper => grouper.phaseName, mapper => mapper);
          const phaseCategorys = Object.getOwnPropertyNames(phaseGroups);
          phaseCategorys.forEach(phaseName => {
            const phaseDivices = Object.getOwnPropertyDescriptor(phaseGroups, phaseName).value;
            this.deviceGroups.push({
              title: phaseName,
              isChecked: false,
              devices: phaseDivices,
            });
          });
          break;
        case DeviceGroupCategoryEnum.byCircuit:
          const circuitGroups = deviceList.GroupBy(grouper => grouper.circuitName, mapper => mapper);
          const circuitCategorys = Object.getOwnPropertyNames(circuitGroups);
          circuitCategorys.forEach(circuitName => {
            const circuitDivices = Object.getOwnPropertyDescriptor(circuitGroups, circuitName).value;
            this.deviceGroups.push({
              title: circuitName,
              isChecked: false,
              devices: circuitDivices,
            });
          });
          break;
        case DeviceGroupCategoryEnum.byModel:
          const modelGroups = deviceList.GroupBy(grouper => grouper.modelName, mapper => mapper);
          const modelCategorys = Object.getOwnPropertyNames(modelGroups);
          modelCategorys.forEach(modelName => {
            const modelDivices = Object.getOwnPropertyDescriptor(modelGroups, modelName).value;
            this.deviceGroups.push({
              title: modelName,
              isChecked: false,
              devices: modelDivices,
            });
          });
          break;
      }
      // 首次加载设备时，对this.selectedDevicesChange的触发
      if (!this.isFristLoadDevice) {
        if (devices.length > 0) {
          // 允许选中多台设备
          if (this.multipleDevice) {
            // 允许选中多台设备，但是对选中的台数做了限制（即this.defaultChooseDeviceCount！=0）
            if (this.defaultChooseDeviceCount) {
              // 允许选中多台设备，允许选中的数量小于设备数量，将对前（this.defaultChooseDeviceCount）设备进行选中
              if (this.defaultChooseDeviceCount < devices.length) {
                const slice = devices.slice(0, this.defaultChooseDeviceCount);
                slice.forEach(device => device.isChecked = true);
                this.selectedDevicesChange.emit(slice);
              } else {  // 允许选中多台设备，允许选中的数量大于设备数量，即对设备全部选中
                devices.forEach(device => device.isChecked = true);
                this.selectedDevicesChange.emit(devices);
              }
            } else if (this.choiceDeviceCount) {

              if (this.choiceDeviceCount < devices.length) {
                const slice = devices.slice(0, this.choiceDeviceCount);
                slice.forEach(device => device.isChecked = true);
                this.selectedDevicesChange.emit(slice);
              } else if (this.selectAGroup) {
                this.deviceGroups[0].devices.forEach(device => device.isChecked = true);
                this.selectedDevicesChange.emit(this.deviceGroups[0].devices);
              } else {  // 允许选中多台设备，允许选中的数量大于设备数量，即对设备全部选中
                devices.forEach(device => device.isChecked = true);
                this.selectedDevicesChange.emit(devices);
              }
            } else if (this.selectedDeviceId != 0) {
              const index = devices.findIndex(device => device.deviceId == this.selectedDeviceId);

              if (index !== -1) {
                this.selectedDevice = devices[index];
              } else {
                this.selectedDevice = devices[0];
              }
              this.selectedDevice.isChecked = true;
              this.selectedDevicesChange.emit([this.selectedDevice]);
            } else if (this.selectedDevice != null) {
              const index = devices.findIndex(device => device.deviceId == this.selectedDevice.deviceId);
              if (index !== -1) {
                this.selectedDevice = devices[index];
              } else {
                this.selectedDevice = devices[0];
              }
              this.selectedDevice.isChecked = true;
              this.selectedDevicesChange.emit([this.selectedDevice]);
            } else {// 允许选中多台设备，不做数量上的限制

              devices.forEach(device => device.isChecked = true);
              this.selectedDevicesChange.emit(devices);
            }
          } else {// 不允许选中多台设备
            if (this.selectedDevice == null && this.selectedDeviceId == 0) {

              this.selectedDevice = devices[0];
              this.selectedDevice.isChecked = true;
            } else {
              if (this.selectedDevice != null) {
                const index = devices.findIndex(device => device.deviceId == this.selectedDevice.deviceId);
                if (index !== -1) {
                  this.selectedDevice = devices[index];
                } else {
                  this.selectedDevice = devices[0];
                }
                this.selectedDevice.isChecked = true;
              }
              if (this.selectedDeviceId != 0) {
                const index = devices.findIndex(device => device.deviceId == this.selectedDeviceId);
                if (index !== -1) {
                  this.selectedDevice = devices[index];
                } else {
                  this.selectedDevice = devices[0];
                }
                this.selectedDevice.isChecked = true;
              }
            }
            this.selectedDevicesChange.emit([this.selectedDevice]);
          }
          this.isFristLoadDevice = true;
        }
      }
    }
  }
  /**
   * 从设备缓存中加载设备
   * @private
   * @param {DeviceCategoryEnum} deviceCategory 设备类别
   * @param {Farm} selectedFarm 电站
   * @returns {Device[]} 设备集合
   * @memberof DeviceSelectorComponent
   */
  private getDevicesFromCache(selectedFarm: Farm): Device[] {
    let result: Device[] = [];
    if (selectedFarm != null) {
      if (this.deviceCache[selectedFarm.farmId] != null) {
        result = this.deviceCache[selectedFarm.farmId];
      }
    }
    return result;
  }
  /**
   * 往设备缓存中写入设备
   *
   * @private
   * @param {DeviceCategoryEnum} deviceCategory 设备类别
   * @param {Farm} selectedFarm 电站
   * @param {Device[]} devices 设备集合
   * @memberof DeviceSelectorComponent
   */
  private setDevicesFromCache(selectedFarm: Farm, devices: Device[]): void {
    if (selectedFarm != null && (devices != null && devices.length > 0)) {
      this.deviceCache[selectedFarm.farmId] = devices;
    }
  }
  /**
   * 将风机对象转化为设备对象
   *
   * @private
   * @param {Turbine} turbine 风机对象
   * @returns {Device} 设备对象
   * @memberof DeviceSelectorComponent
   */
  private turbineConverToDevice(turbine: Device): Device {
    return new Device(
      turbine.deviceId,
      1,
      turbine.farmId,
      turbine.phaseId,
      turbine.circuitId,
      turbine.modelId,
      0,
      turbine.deviceCode,
      turbine.deviceName,
      turbine.longitude,
      turbine.latitude,
      turbine.elevation,
      turbine.turBenchMark,
      0,
      null,
      '01',
      '风机',
      turbine.circuitName,
      turbine.phaseName,
      turbine.farmCode,
      turbine.farmName,
      turbine.modelName,
      '',
      0,
      [],
      false
    );
  }
  private getCheckedDevices(): Device[] {
    const checkedDevices: Device[] = [];
    const farmIdStrings = Object.getOwnPropertyNames(this.deviceCache);
    farmIdStrings.forEach(farmIdString => {
      const farmId: number = parseInt(farmIdString, 0);
      if (farmId !== null) {
        const farmDevices = this.deviceCache[farmId];
        farmDevices.forEach(device => {
          if (device.isChecked) {
            checkedDevices.push(device);
          }

        });
      }

    });
    return checkedDevices;
  }

}

/**
 * 设备缓存
 *
 * @export
 * @interface DeviceCache
 */
export interface DeviceCache {
  [index: number]: Device[];
}
/**
 * 设备分组类别
 *
 * @export
 * @enum {number}
 */
export enum DeviceGroupCategoryEnum {
  none = 0,
  byPhase = 1,
  byCircuit = 2,
  byModel = 3,
}



// WEBPACK FOOTER //
// ./src/app/module/common/device-tag-selector/device-selector/device-selector.component.ts